// src/features/messages/api/use-get-messages.ts
import {MARK_DATA_URL} from "@/lib/social/constants";

const BATCH_SIZE = 20

interface Props {
    channelId?: string
    conversationId?: string
    parentMessageId?: string
}

export const useGetMessages = async ({channelId, conversationId, parentMessageId}: Props) => {
    // const [page, setPage] = useState(1)
    // const [status, setStatus] = useState('')
    console.log(channelId, conversationId, parentMessageId)
    let status: 'ok' | 'loading' | 'loadingFirstPage' | 'loadingMore' | 'error' | 'canLoadMore' | string = ''

    const get = async (page: number, curStatus?: string) => {
        if (curStatus) status = curStatus
        else status = 'loading'
        if (page != 1) status = 'loadingMore'
        else status = 'loadingFirstPage'

        const res = await fetch(
            `/api/messages?_page=${page.toString()}&_per_page=${BATCH_SIZE}` +
            // `${MARK_DATA_URL}/messages?_page=${page.toString()}&_per_page=${BATCH_SIZE}` +
            `${channelId ? ('&channelId=' + channelId) : ''}` +
            `${conversationId ? ('&conversationId=' + conversationId) : ''}` +
            `${parentMessageId ? ('&parentMessageId=' + parentMessageId) : ''}`,
        )
        if (res.ok) status = 'ok'

        const data = await res.json()
        if (page <= data.pages) status = 'canLoadMore'
        // console.log(data)
        // setPage((prev) => prev + 1)

        console.log('use get messages', data)

        return data
    }
    // const data = await get(page)
    const data = await get(1) // json-server从page 1开始

    return {
        data,
        status,
        loadMode: get
    }
}